package com.mobile.collect.utils;

import android.text.TextUtils;

import com.mobile.collect.beans.TypeInfo;
import com.mobile.collect.beans.DescribeInfo;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.List;

/**
 * 类名: XMLUtil
 * 作者: 李学伟
 * 日期: 2020年09月23日 18:23
 * 描述:
 */
public class XMLUtil {
    public Element root;

    public XMLUtil(String xml) {
        try {
            Document doc = DocumentHelper.parseText(xml);
            root = doc.getRootElement();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public List<TypeInfo> parserChildType() {
        List<TypeInfo> dataList = new ArrayList<>();
        List<Element> list = root.elements();
        for (Element element : list) {
            String typeCode = element.attributeValue("typeCode");
            String typeName = element.attributeValue("typeName");
            String childCode = element.attributeValue("childCode");
            String childName = element.attributeValue("childName");
            TypeInfo typeInfo = new TypeInfo(typeCode, typeName, childCode, childName);
            dataList.add(typeInfo);
        }
        return dataList;
    }


    public List<DescribeInfo> parserDescType() {
        return paramerDescribeInfo(root);
    }


    private List<DescribeInfo> paramerDescribeInfo(Element rootElement) {
        List<Element> list = rootElement.elements();
        List<DescribeInfo> listDatas = new ArrayList<>();
        for (Element element : list) {
            String name;
            name = element.attributeValue("name");
            if (TextUtils.isEmpty(name)) {
                name = element.getText();
            }
            DescribeInfo info = new DescribeInfo(name);
            listDatas.add(info);
            if (element.elements().size() != 0) {
                List<DescribeInfo> childList = paramerDescribeInfo(element);
                info.setChildList(childList);
            }
        }
        return listDatas;
    }


}
